<template>
  <div class="manager-list-container">
    <!-- 搜索区域 -->
    <a-card class="search-card">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="邮箱">
          <a-input 
            v-model:value="searchForm.email" 
            placeholder="请输入邮箱" 
            style="width: 200px"
            allowClear
            @pressEnter="handleSearch"
          />
        </a-form-item>

        <!-- <a-form-item label="类型">
          <a-select 
            v-model="searchForm.type" 
            placeholder="请选择类型" 
            style="width: 120px"
            allowClear
          >
            <a-select-option value="1">超级管理员</a-select-option>
            <a-select-option value="2">普通管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select 
            v-model="searchForm.is_enable" 
            placeholder="请选择状态" 
            style="width: 120px"
            allowClear
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item>
          <a-button type="primary" @click="handleSearch">搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 16px">
      <a-button type="primary" @click="handleAdd">添加管理员</a-button>
    </div>

    <!-- 管理员列表 -->
    <a-card class="manager-table">
      <a-table
        :columns="columns"
        :data-source="managerList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :scroll="{ x: 1200 }"
        :locale="{ emptyText: '暂无管理员数据' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 1 ? 'red' : 'blue'">
              {{ record.type === 1 ? '超级管理员' : '普通管理员' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'is_enable'">
            <a-tag :color="record.is_enable ? 'green' : 'red'">
              {{ record.is_enable ? '启用' : '禁用' }}
            </a-tag>
          </template>

        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑管理员模态框 -->
    <a-modal
      :open="modalVisible"
      :title="isEdit ? '编辑管理员' : '添加管理员'"
      width="600px"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <a-form-item label="邮箱" name="email" :rules="[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入正确的邮箱格式' }]">
          <a-input v-model:value="form.email" placeholder="请输入邮箱" :disabled="isEdit" />
        </a-form-item>
        

        <a-form-item label="密码" name="password" :rules="isEdit ? [] : [{ required: true, message: '请输入密码' }]">
          <a-input-password v-model:value="form.password" :placeholder="isEdit ? '留空则不修改密码' : '请输入密码'" />
        </a-form-item>
        
        <a-form-item label="管理员类型" name="type" :rules="[{ required: true, message: '请选择管理员类型' }]">
          <a-select v-model:value="form.type" placeholder="请选择管理员类型">
            <a-select-option :value="1">超级管理员</a-select-option>
            <a-select-option :value="2">普通管理员</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="状态" name="is_enable">
          <a-radio-group v-model:value="form.is_enable">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 修改密码模态框 -->
    <a-modal
      :open="passwordModalVisible"
      title="修改密码"
      width="500px"
      @ok="handlePasswordSubmit"
      @cancel="handlePasswordCancel"
      :confirm-loading="passwordLoading"
    >
      <a-form
        :model="passwordForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <a-form-item label="旧密码" name="old_password" :rules="[{ required: true, message: '请输入旧密码' }]">
          <a-input-password v-model:value="passwordForm.old_password" placeholder="请输入旧密码" />
        </a-form-item>
        
        <a-form-item label="新密码" name="new_password" :rules="[{ required: true, message: '请输入新密码' }]">
          <a-input-password v-model:value="passwordForm.new_password" placeholder="请输入新密码" />
        </a-form-item>
        
        <a-form-item label="确认密码" name="confirm_password" :rules="[{ required: true, message: '请确认新密码' }]">
          <a-input-password v-model:value="passwordForm.confirm_password" placeholder="请确认新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { managerApi } from '@/api/manager'

export default defineComponent({
  name: 'ManagerListView',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const managerList = ref([])
    const searchForm = reactive({
      email: '',
      type: undefined,
      is_enable: undefined
    })
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 20,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) => `共 ${total} 条记录`
    })
    
    // 表格列配置
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
        width: 200
      },

      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 120
      },
      {
        title: '状态',
        dataIndex: 'is_enable',
        key: 'is_enable',
        width: 100
      },


    ]
    
    // 获取管理员列表
    const fetchManagerList = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          per_page: pagination.pageSize,
          ...searchForm
        }
        
        const response = await managerApi.getList(params)
        
        if (response && response.code === 200) {
          managerList.value = response.data.data || []
          pagination.total = response.data.total || 0
        } else {
          message.error(response?.message || '获取管理员列表失败')
        }
      } catch (error) {
        console.error('获取管理员列表失败:', error)
        message.error('获取管理员列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchManagerList()
    }
    
    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        email: '',
        type: undefined,
        is_enable: undefined
      })
      pagination.current = 1
      fetchManagerList()
    }
    
    // 表格变化
    const handleTableChange = (pag) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      fetchManagerList()
    }
    
    // 添加/编辑相关
    const modalVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const form = reactive({
      id: null,
      email: '',
      password: '',
      type: 2,
      is_enable: 1
    })
    
    const handleAdd = () => {
      isEdit.value = false
      Object.assign(form, {
        id: null,
        email: '',
        password: '',
        type: 2,
        is_enable: 1
      })
      modalVisible.value = true
    }
    

    
    const handleSubmit = async () => {
      if (!form.email) {
        message.error('请输入邮箱')
        return
      }
      if (!form.name) {
        message.error('请输入姓名')
        return
      }
      if (!isEdit.value && !form.password) {
        message.error('请输入密码')
        return
      }
      
      submitLoading.value = true
      try {
        let response
        if (isEdit.value) {
          const updateData = {
            id: form.id,
            is_enable: form.is_enable
          }
          if (form.password) {
            updateData.password = form.password
          }
          response = await managerApi.update(updateData)
        } else {
          response = await managerApi.add({
            email: form.email,
            name: form.name,
            password: form.password,
            type: form.type,
            is_enable: form.is_enable
          })
        }
        
        if (response && response.code === 200) {
          message.success(isEdit.value ? '管理员更新成功' : '管理员添加成功')
          modalVisible.value = false
          fetchManagerList()
        } else {
          message.error(response?.message || (isEdit.value ? '管理员更新失败' : '管理员添加失败'))
        }
      } catch (error) {
        console.error('操作失败:', error)
        message.error(isEdit.value ? '管理员更新失败' : '管理员添加失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    const handleCancel = () => {
      modalVisible.value = false
    }
    

    

    
    // 修改密码相关
    const passwordModalVisible = ref(false)
    const passwordLoading = ref(false)
    const passwordForm = reactive({
      old_password: '',
      new_password: '',
      confirm_password: ''
    })
    
    const handlePasswordSubmit = async () => {
      if (!passwordForm.old_password) {
        message.error('请输入旧密码')
        return
      }
      if (!passwordForm.new_password) {
        message.error('请输入新密码')
        return
      }
      if (passwordForm.new_password !== passwordForm.confirm_password) {
        message.error('两次输入的密码不一致')
        return
      }
      
      passwordLoading.value = true
      try {
        const response = await managerApi.changePassword({
          old_password: passwordForm.old_password,
          new_password: passwordForm.new_password
        })
        
        if (response && response.code === 200) {
          message.success('密码修改成功')
          passwordModalVisible.value = false
          handlePasswordCancel()
        } else {
          message.error(response?.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改失败:', error)
        message.error('密码修改失败')
      } finally {
        passwordLoading.value = false
      }
    }
    
    const handlePasswordCancel = () => {
      passwordModalVisible.value = false
      Object.assign(passwordForm, {
        old_password: '',
        new_password: '',
        confirm_password: ''
      })
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchManagerList()
    })
    
    return {
      loading,
      managerList,
      searchForm,
      pagination,
      columns,
      fetchManagerList,
      handleSearch,
      handleReset,
      handleTableChange,
      modalVisible,
      submitLoading,
      isEdit,
      form,
      handleAdd,
      handleSubmit,
      handleCancel,
      passwordModalVisible,
      passwordLoading,
      passwordForm,
      handlePasswordSubmit,
      handlePasswordCancel,
      formatDate
    }
  }
})
</script>

<style scoped>
.manager-list-container {
  padding: 20px;
  background: #ffffff;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 16px;
  box-shadow: none;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.manager-table {
  background: white;
  border-radius: 6px;
  box-shadow: none;
  border: 1px solid #e8e8e8;
}

.manager-table :deep(.ant-table) {
  table-layout: fixed;
}

.manager-table :deep(.ant-table-tbody > tr > td) {
  vertical-align: middle;
  height: 50px;
  padding: 12px 16px !important;
  border-bottom: 1px solid #f0f0f0;
}

.manager-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #e8e8e8;
  padding: 12px 16px !important;
}


</style>